package homebuh.model
{
	import homebuh.model.vo.LoginVO;
	import homebuh.model.webservices.HomebuhWebService;
	import homebuh.model.webservices.LoginResultEvent;
	import homebuh.model.webservices.User;
	
	import mx.managers.CursorManager;
	import mx.messaging.messages.ErrorMessage;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.soap.WebService;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	public class LoginProxy extends Proxy implements IProxy
	{
		private static const AuthorizationError : String = "Authorization failed";
		private static const ConnectToServerError : String = "Unable to connect to server";
		
		public static const NAME:String = 'loginProxy';
		
		public static const LOGIN_FAILED: String = "loginFailed";
		public static const LOGIN_SUCCESS: String = "loginSucces";	

		private var loginService: HomebuhWebService;

		public var faultMessage: String;

		private var appProxy: ApplicationProxy;
		
		public function LoginProxy(data:Object=null) 
		{
			super(NAME, new LoginVO());
			
			appProxy = facade.retrieveProxy(ApplicationProxy.NAME) as ApplicationProxy;

			loginService = new HomebuhWebService(WebService.DEFAULT_DESTINATION_HTTPS);
			loginService.getWebService().useProxy = false;

			loginService.addloginEventListener(onLoginResult);
			loginService.addEventListener(FaultEvent.FAULT, onFault);
		}
		
		public function getUser(vo: LoginVO):void
		{
			loginService.getWebService().setBasicHttpAuthorization(vo.login, vo.password);
			loginService.login(vo.login);		
			CursorManager.setBusyCursor();
		}

		private function onLoginResult(event: LoginResultEvent):void
		{
			CursorManager.removeBusyCursor();
			
			var user: User = event.result as User
			setData(user);

			appProxy.viewState = ApplicationProxy.LOGGED_IN_STATE;
			sendNotification(LoginProxy.LOGIN_SUCCESS);
		}

		private function onFault(event: FaultEvent): void 
		{
			faultMessage = event.statusCode != 0 ? AuthorizationError : ConnectToServerError;
			
			CursorManager.removeBusyCursor();

			appProxy.viewState = ApplicationProxy.LOGIN_ERROR_STATE;	
			sendNotification(LoginProxy.LOGIN_FAILED);
		}
		
		public function get loginVO(): LoginVO
		{
			return data as LoginVO;
		}				
	}
}